import React from 'react';
import { inject, observer } from 'mobx-react';
import { Spin, Button, Icon, Modal, Table, message } from 'antd';
import { WeaPopoverHrm, WeaNewScroll, WeaSearchGroup, WeaFormItem, WeaInput, WeaRichText, WeaTableEditable, WeaLocaleProvider, WeaSelect, WeaDialog, WeaRightMenu } from 'ecCom';
import * as Util from '../../util/Util';

const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;

@inject('knowledgeEditStore')
@observer
export default class KnowledgeEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [
                {
                    title: <span>{getLabel(229, '标题')}</span>,
                    dataIndex: 'title',
                    key: 'title',
                    width: '*',
                    com: [
                        { type: 'INPUT', viewAttr: 3, key: 'title', placeholder: getLabel(229, '标题'), viewAttr: 2, defaultValue: '' },
                    ],
                },
                {
                    title: <span>{getLabel(17908, '指定知识文档')}</span>,
                    dataIndex: 'docIds',
                    key: 'docIds',
                    width: '20%',
                    com: [
                        { type: 'BROWSER', key: 'docIds', browserConditionParam: { type: 9, isSingle: false }, viewAttr: 2, defaultValue: '' },
                    ],
                },
                {
                    title: <span>{getLabel(23209, '动态参考文档')}</span>,
                    dataIndex: 'sqlstr',
                    key: 'sqlstr',
                    width: '20%',
                    com: [
                        { type: 'TEXTAREA', key: 'sqlstr', placeholder: getLabel(23209, '动态参考文档'), viewAttr: 2, defaultValue: '' },
                    ],
                },
                {
                    title: <span>{getLabel(6071, '权重')}(%)</span>,
                    dataIndex: 'rate',
                    key: 'rate',
                    width: '20%',
                    com: [
                        { type: 'INPUTNUMBER', key: 'rate', defaultValue: 0, viewAttr: 2 },
                    ],
                },
                {
                    title: <span>{getLabel(338, '排序')}</span>,
                    dataIndex: 'sort',
                    key: 'sort',
                    width: '20%',
                    com: [
                        { type: 'INPUTNUMBER', key: 'sort', defaultValue: 0, viewAttr: 2 },
                    ],
                },
            ],
            columnsKnowledgeType: [
                {
                    title: <span>{getLabel(195, '名称')}</span>,
                    dataIndex: 'name',
                    key: 'name',
                    width: '*',
                    com: [
                        { type: 'INPUT', viewAttr: 3, key: 'name', placeholder: getLabel(195, '名称'), viewAttr: 2, defaultValue: '' },
                    ],
                },
                {
                    title: <span>{getLabel(338, '排序')}</span>,
                    dataIndex: 'dsporder',
                    key: 'dsporder',
                    width: '50%',
                    com: [
                        { type: 'INPUT', viewAttr: 3, key: 'dsporder', placeholder: getLabel(338, '排序'), viewAttr: 2, defaultValue: '' },
                    ],
                },
            ],
            refeshid: -1,
            viewHeight: this.getHeight(),
            knowledgeId: '', // || this.props.knowledgeId
            operation: '', // || this.props.operation
            selectedRowKeys: [],
            visibleKnowledgeType: false,
            ckConfig: {
                toolbar: [
                    { name: 'document', items: ['Source'] },
                    { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList'] },
                    { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
                    { name: 'colors', items: ['TextColor'] },
                    { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] },
                    { name: 'insert', items: ['Table', 'Image', 'Smiley'] },
                ],
                uploadUrl: '/api/knowledge/knowledgeMap/uploadDoc?category=6604', // 上传地址
                height: 150,
                autoGrow_minHeight: 150,
                autoGrow_maxHeight: 150,
            },
            detailValidator: {
                rules: {
                    title: 'required',
                },
                errorMessage: {
                    required: '此项必填',
                },
            },
            validator: {
                rules: {
                    name: 'required',
                    dsporder: 'required',
                },
                errorMessage: {
                    required: '此项必填',
                },
            },
            rightMenuDatas:[
                {
                    key: '1',
                    icon: <i className="icon-coms-save" />,
                    content: '保存',
                    onClick: this.saveKnowledgeType,
                },
            ]
        };
        this.isfresh = true;
    }
    componentWillMount() { // 一些初始化请求
        this.initKnowledgePage(this.props);
    }
    componentWillUnmount() {
        this.cleanValues();
    }
    componentWillReceiveProps(newProps) {
        if (newProps.operation == 'add') {
            this.cleanValues();
        }
        this.initKnowledgePage(newProps);
    }

    cleanValues() {
        let { knowledgeEditStore } = this.props;
        knowledgeEditStore.name = '';
        knowledgeEditStore.remark = '';
        knowledgeEditStore.datas = [];
    }


    initKnowledgePage(props) {
        const { knowledgeEditStore } = this.props;
        let { columns } = this.state;
        let operation = Util.getParams('operation') || props.operation;
        let knowledgeId = Util.getParams('knowledgeId') || props.knowledgeId;
        this.setState({ knowledgeId, operation });
        if (operation == 'edit' || operation == 'add') {
            columns.map((element, index) => {
                element.com[0].viewAttr = 2;
            });
        } else if (operation == 'view') {
            columns.map((element, index) => {
                element.com[0].viewAttr = 1;
            });
        }
        if (knowledgeId) {
            knowledgeEditStore.getKnowledgeDetail({ knowledgeId });
        }
    }

    editData=()=> {
        let { columns } = this.state;
        this.setState({ operation: 'edit' });
        columns.map((element, index) => {
            element.com[0].viewAttr = 2;
        });
    }

    saveData=()=> {
        const { knowledgeEditStore } = this.props;
        let { name, remark, datas } = knowledgeEditStore;
        let { operation, knowledgeId } = this.state;
        const result = this.refs.tableEdit.doValidate();
        let passStatues = result.pass;
        if (!passStatues) {
            return;
        }
        let sumRate = 0;
        for (let i = 0; i < datas.length; i++) {
            sumRate += parseFloat(datas[i].rate);
        }
        if (name.length == 0) {
            Modal.error({
                title: '提示',
                content: '知识点名称不能为空!',
            });
            return;
        }
        if (datas.length > 0 && sumRate != 100) {
            Modal.error({
                title: '提示',
                content: '明细权重填写不正确!',
            });
            return;
        }
        let _this = this;
        knowledgeEditStore.saveKnowledge({
            name,
            remark,
            datas: JSON.stringify(datas),
            operation,
            knowledgeId,
            doback(knowledgeId) {
                message.success('保存成功!', 2);
                let optparams = [];
                optparams.rowid = knowledgeId;
                optparams.opttype = operation;
                optparams.type = ['name'];
                optparams.value = [knowledgeEditStore.name];
                if (typeof _this.props.onCallBackSuccess === 'function') {
                    _this.props.onCallBackSuccess(optparams);
                }
            },
        });
    }

    getHeight() {
        let { minusHeight } = this.props;
        if (minusHeight == undefined) {
            minusHeight = 0;
        }
        return window.innerHeight - 110 - minusHeight;
    }

    onRemarkChange = (values) => {
        const { knowledgeEditStore } = this.props;
        knowledgeEditStore.setState({ remark: values });
    }

    onNameChange = (values) => {
        const { knowledgeEditStore } = this.props;
            knowledgeEditStore.setState({ name: values });
    }

    // 添加一行表格数据
    willAdd(datas, addData, type) {
        const { knowledgeEditStore } = this.props;
        if (type == 'datas') {
            let length = datas.length;
            datas[length - 1].klist = [];
            knowledgeEditStore.datas = datas;
        } else if (type == 'knowledgetypelist') {
            knowledgeEditStore.knowledgetypelist = datas;
        }
    }

    knowledgeDetailWillAdd=(datas)=> {
        const { knowledgeEditStore } = this.props;
        let length = datas.length;
        datas[length - 1].klist = [];
        knowledgeEditStore.setState({datas:datas});
    }

    knowledgeTypeWillAdd=(datas)=>{
        const { knowledgeEditStore } = this.props;
        knowledgeEditStore.setState({knowledgetypelist:datas});
    }

    // 删除表格数据
    doDelete = (datas, keys, type) => {
        const { knowledgeEditStore } = this.props;
        return new Promise((resolve, reject) => {
            Modal.confirm({
                content: '确定要删除吗？ ',
                onOk: () => {
                    resolve(true);
                    let list = [...knowledgeEditStore[type]];
                    for (let j = 0; j < list.length; j++) {
                        for (let i = 0; i < keys.length; i++) {
                            if (list[j].id == keys[i]) {
                                knowledgeEditStore[type].remove(list[j]);
                            }
                        }
                    }
                },
                onCancel: () => {
                    resolve(false);
                },
            });
        });
    }

    knowledgeDetaildoDelete=(datas, keys)=>{
       this.doDelete(datas,keys,"datas");
    }

    knowledgeTypedoDelete=(datas, keys)=>{
        this.doDelete(datas,keys,"knowledgetypelist");
    }

    onRowSelect = (selectedRowKeys) => {
        this.setState({ selectedRowKeys });
    };
    // 复制单元格
    willCopy=(datas, selectedKeys, copyDatas)=> {
        const { knowledgeEditStore } = this.props;
        knowledgeEditStore.datas = datas;
    }
    // 编辑单元格回调
    willEdit=(datas, result, type)=> {
        let tip = '';
        let days = 0;
        let flag = false;
        const { key, record, value, index } = result;
        if (flag) {
            if (tip.length > 0) {
                Modal.warning({
                    title: '提示',
                    content: tip,
                });
            }
            datas[index] = record;
            const { knowledgeEditStore } = this.props;
            knowledgeEditStore[type] = datas;
        } else {
            const { knowledgeEditStore } = this.props;
            knowledgeEditStore[type] = datas;
        }
    }
    knowledgeTypeWillEdit=(datas, result)=>{
     this.willEdit(datas, result, 'knowledgetypelist');
    }

    knowledgeDetailWillEdit=(datas, result)=>{
        this.willEdit(datas, result,"datas");
    }
    renderDetail=()=> {
        if (this.isfresh) {
            this.isfresh = false;
            const { knowledgeEditStore } = this.props;
            this.setState({ knowledgeId: this.props.knowledgeId, refeshid: this.props.refeshid });
            knowledgeEditStore.getKnowledgeDetail({ knowledgeId: this.props.knowledgeId });
        }
    }

    saveKnowledgeType=()=> {
        const { knowledgeEditStore } = this.props;
        const result = this.table.doValidate();
        knowledgeEditStore.knowledgetypelist.forEach((element) => {
            if (window.isNaN(element.dsporder)) {
                element.dsporder = '';
                // message.error("排序内容只能为数字！");
                result.pass = false;
            }
        });
        if (result.pass) {
            knowledgeEditStore.saveKnowledgeType({
                knowledgetypelist: JSON.stringify(knowledgeEditStore.knowledgetypelist),
                doback() {
                    message.success('保存成功！');
                },
            });
        }
    }
    onTypeChange = (v) => {
        let { knowledgeEditStore } = this.props;
            knowledgeEditStore.setState({ knowledgetype: v })
    }
    editType=()=> {
        this.setState({ visibleKnowledgeType: true })
    }


    render() {
        let { knowledgeEditStore, _minusHeight } = this.props;
        if (_minusHeight == undefined) {
            _minusHeight = 0;
        }
        const { viewHeight, columns, operation, knowledgeId, refeshid, visibleKnowledgeType, columnsKnowledgeType } = this.state;
        const { loading, name, remark, datas, hasRight, knowledgetypeOption, knowledgetype, knowledgetypelist } = knowledgeEditStore;
        if ((knowledgeId != this.props.knowledgeId || refeshid != this.props.refeshid) && (operation == 'edit' || operation == 'view')) {
            this.isfresh = true;
            this.renderDetail();
        }
        return (
            <div className="knowledge-knowledge-edit">
                <div className="knowledge-edit-title-div">
                    <div className="title-Incon"><span className="icon-coms-doc" style={{ fontSize: '16px', float: 'left' }} /><b className="title-Incon-name">知识点信息</b></div>
                    {((operation == 'edit' && hasRight == true) || operation == 'add') && <div className="title-save" onClick={this.saveData}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@z7awr1`} type="save" /><b className="title-save-name">保存</b></div>}
                    {operation == 'view' && hasRight == true && <div className="title-save" onClick={this.editData}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@ygzl94`} type="edit" /><b className="title-save-name">编辑</b></div>}
                </div>
                <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@cbtb9d`} height={viewHeight - _minusHeight} >
                    <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@x4ypan`} />
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@vkl28v`} spinning={loading}>
                        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@bgyeau`} title={getLabel(1361, '基本信息')} needTigger={false} showGroup={true}>
                            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@z16fzq`} labelCol={{ span: 4 }} wrapperCol={{ span: 17 }} className="iteamClass" label={getLabel(27915, '知识点名称')} >
                                <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@t1ydtu`} value={name} viewAttr={operation == 'view' ? '1' : '3'} onChange={this.onNameChange} />
                            </WeaFormItem>
                            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@690myx`} labelCol={{ span: 4 }} wrapperCol={{ span: 17 }} className="iteamClass" label={getLabel(27915, '知识点描述')} >
                                <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@7iar0d`}
                                    viewAttr={operation == 'view' ? 1 : 2}
                                    value={remark}
                                    style={{ marginTop: '20px', marginLeft: '20px', marginRight: '20px', width: '96%' }}
                                    ckConfig={this.state.ckConfig}
                                    onChange={this.onRemarkChange}
                                />
                            </WeaFormItem>
                            
                        </WeaSearchGroup >
                        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@zv6m12`} title={getLabel(27915, '知识点明细')} needTigger={false} showGroup={true}>
                            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@lm58su`}
                                viewAttr={operation == 'view' ? 1 : 2}
                                ref="tableEdit"
                                columns={columns}
                                datas={toJS(datas)}
                                selectedRowKeys={this.state.selectedRowKeys}
                                willAdd={this.knowledgeDetailWillAdd}
                                willDelete={this.knowledgeDetaildoDelete}
                                onRowSelect={this.onRowSelect}
                                willEdit={this.knowledgeDetailWillEdit}
                                willCopy={this.willCopy}
                                validator={this.state.detailValidator}
                            />
                        </WeaSearchGroup>
                        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@4emcyx`}
                            onCancel={() => this.setState({ visibleKnowledgeType: false })}
                            title={getLabel(27915, '知识点') + getLabel(455, '分类')}
                            visible={visibleKnowledgeType}
                            style={{ width: 1000, height: this.getHeight() + 110 }}
                            hasScroll
                            buttons={[<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w9w3n4@save`} type="primary" onClick={this.saveKnowledgeType}>保存</Button>]}
                        >   <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@7mgva4`} datas={this.state.rightMenuDatas}
                        >
                                <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@rpivlq`}
                                    ref={(el) => {
                                        this.table = el;
                                    }}
                                    columns={columnsKnowledgeType}
                                    datas={toJS(knowledgetypelist)}
                                    showCopy={false}
                                    willAdd={this.knowledgeTypeWillAdd}
                                    willDelete={this.knowledgeTypedoDelete}
                                    willEdit={this.knowledgeTypeWillEdit}
                                    validator={this.state.validator}
                                />
                            </WeaRightMenu>
                        </WeaDialog>
                    </Spin>
                </WeaNewScroll>
            </div >
        );
    }
}
